package com.myspring.resttest;
import java.text.ParseException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.beans.TypeMismatchException;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.HandlerMapping;

import com.myspring.resttest.error.RestError;
import com.myspring.resttest.request.classes.IpPoolRequest;


@RestController
public class IpPoolController {
	Logger logger = Logger.getLogger(IpPoolController.class);
	HttpStatus respStatus = HttpStatus.OK;
	@RequestMapping(value="ippool/{poolname}", method = RequestMethod.GET)
	public IpPoolRequest getIpPoolInfo(@PathVariable("poolname")String poolName) throws Exception {
		logger.info("Pool name queried is "+poolName);
		if (poolName.contains("$")) {
			throw new Exception("invalid poolname specified");
		}
		if (poolName.equals("kanwaljeet")) {
			throw new Exception("this pool can never exist");
		}
		RestError error = new RestError(HttpStatus.OK, 0, "Success");
		IpPoolRequest poolr = new IpPoolRequest();
		poolr.setName("dummyPool");
		poolr.setErrorResponse(error);
		return poolr;
	}
	
	@ExceptionHandler(Exception.class)
	//@ResponseStatus(value=respStatus)
	@ResponseBody
	public RestError handleTypeMisMatchException(HttpServletRequest req, HttpServletResponse res, Exception ex) {
		String restOfUrl = (String) req.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE);
		logger.error("Rest of url is "+restOfUrl);
		//res.setStatus(HttpStatus.NOT_FOUND);
		return new RestError(HttpStatus.NOT_FOUND, 0, ex.getMessage());
	}
}
